package vue.panneau3;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JPanel;

import vue.Application;


import com.jme.bounding.BoundingBox;
import com.jme.image.Texture;
import com.jme.input.InputHandler;
import com.jme.input.KeyInput;
import com.jme.input.action.InputAction;
import com.jme.input.action.InputActionEvent;
import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.renderer.Renderer;
import com.jme.scene.shape.Box;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jme.util.TextureManager;
import com.jmex.awt.JMECanvas;
import com.jmex.awt.JMECanvasImplementor;
import com.jmex.awt.SimpleCanvasImpl;
import com.jmex.awt.input.AWTMouseInput;


public class Representation3D extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	Canvas comp = null;
    JMECanvasImplementor impl;
	
	public Representation3D() {
		super() ;
		this.setLayout(new BorderLayout()) ;
	
        // make the canvas:
        comp = DisplaySystem.getDisplaySystem("lwjgl").createCanvas(500,500);

	
        // add a listener... if window is resized, we can do something about it.
        comp.addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent ce) {
                //doResize();
            }
        });
        KeyInput.setProvider( KeyInput.INPUT_AWT );
        AWTMouseInput.setup( comp, false );

                // Important!  Here is where we add the guts to the panel:
        impl = new MyImplementor(500, 500);
        JMECanvas jmeCanvas = ( (JMECanvas) comp );
        jmeCanvas.setImplementor(impl);
        jmeCanvas.setUpdateInput( true );

        this.add(comp,BorderLayout.CENTER) ;
        
        // MAKE SURE YOU REPAINT SOMEHOW OR YOU WON'T SEE THE UPDATES...
        new Thread() {
            { setDaemon(true); }
            public void run() {
                while (true) {
                    comp.repaint();
                    yield();
                    try {
						Thread.sleep(30) ;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
                }
            }
        }.start();

	}

	
	@Override
	public Dimension getPreferredSize() {
		return new Dimension(600,300);
	}
	
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
	}
	
}




// IMPLEMENTING THE SCENE:

class MyImplementor extends SimpleCanvasImpl {

    private Quaternion rotQuat;
    private float angle = 0;
    private Vector3f axis;
    private Box box;
	long startTime = 0;
	long fps = 0;
    private InputHandler input;

    public MyImplementor(int width, int height) {
        super(width, height);
    }

    public void simpleSetup() {

        // Normal Scene setup stuff...
        rotQuat = new Quaternion();
        axis = new Vector3f(1, 1, 0.5f);
        axis.normalizeLocal();

        Vector3f max = new Vector3f(5, 5, 5);
        Vector3f min = new Vector3f(-5, -5, -5);

        box = new Box("Box", min, max);
        box.setModelBound(new BoundingBox());
        box.updateModelBound();
        box.setLocalTranslation(new Vector3f(0, 0, -10));
        box.setRenderQueueMode(Renderer.QUEUE_SKIP);
        rootNode.attachChild(box);

        box.setRandomColors();

        TextureState ts = renderer.createTextureState();
        ts.setEnabled(true);
        ts.setTexture(TextureManager.loadTexture(Application.class
                .getResource(
                        "img/splashSimplexe.gif"),
                Texture.MM_LINEAR, Texture.FM_LINEAR));

        rootNode.setRenderState(ts);
        startTime = System.currentTimeMillis() + 5000;

        input = new InputHandler();
        input.addAction( new InputAction() {
            public void performAction( InputActionEvent evt ) {
                System.out.println( evt.getTriggerName() );
            }
        }, InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_ALL, InputHandler.AXIS_NONE, false );
    }

    public void simpleUpdate() {
        input.update( tpf );

        // Code for rotating the box... no surprises here.
        if (tpf < 1) {
            angle = angle + (tpf * 25);
            if (angle > 360) {
                angle = 0;
            }
        }
        rotQuat.fromAngleNormalAxis(angle * FastMath.DEG_TO_RAD, axis);
        box.setLocalRotation(rotQuat);
        
		if (startTime > System.currentTimeMillis()) {
			fps++;
		} else {
			long timeUsed = 5000 + (startTime - System.currentTimeMillis());
			startTime = System.currentTimeMillis() + 5000;
//			System.out.println(fps + " frames in " + (timeUsed / 1000f) + " seconds = "
//					+ (fps / (timeUsed / 1000f))+" FPS (average)");
			fps = 0;
		}				
    }
}